package com.example.mapping.manage.visit;

import com.example.mapping.entity.visit.JsonMappingVisitInfo;
import com.example.mapping.enumeration.VisitorTypeEnum;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Objects;

/**
 * json遍历访问者
 *
 * @author baoyoujia
 * @date 2022/10/20
 */
@Component
public class JsonTraverseVisitor implements Visitor {

    @Override
    public void visit(JsonMappingVisitInfo jsonMappingVisitInfo) {
        JsonNode node = jsonMappingVisitInfo.getNode();
        if (Objects.isNull(node)) {
            return;
        }
        if (node.isArray()) {
            for (JsonNode jsonNode : node) {
                jsonMappingVisitInfo.setNode(jsonNode);
                jsonMappingVisitInfo.execute(this);
            }
        }
        if (node.isObject()) {
            boolean has = node.has(jsonMappingVisitInfo.getName());
            if (has) {
                jsonMappingVisitInfo.addNodes(node);
            } else {
                Iterator<JsonNode> elements = node.elements();
                while (elements.hasNext()) {
                    JsonNode jsonNode = elements.next();
                    jsonMappingVisitInfo.setNode(jsonNode);
                    jsonMappingVisitInfo.execute(this);
                }
            }
        }
    }

    @Override
    public VisitorTypeEnum getType() {
        return VisitorTypeEnum.TRAVERSE;
    }


}
